@using viBook.Models
@model Book
@{
    var categories = ViewBag.CategoryCollection as IEnumerable<SelectListItem>;
    string imageUrl = string.IsNullOrEmpty(@Model.CoverUrl) ? "/Content/DefaultbookImage.png" : @Model.CoverUrl;
    var returnUrl = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : Url.Action("Index", "Account");
}
@* This partial view defines form fields that will appear when creating and editing entities *@
<script src="../../Scripts/jquery.autocomplete.min.js" type="text/javascript"> </script>
<link href="../../Content/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<link href="../../Scripts/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/Style.css")" rel="stylesheet" type="text/css" />
<script src="../../Scripts/uploadify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"> </script>
<script src="../../Scripts/uploadify/swfobject.js" type="text/javascript"> </script>
@using (Html.BeginForm("Edit", "Books", FormMethod.Post, new {id = "CreateBookForm", @class = "gen-form with-messages"}))
{
    <div id="main">
        <ul class="tabs">
            <li class="active"><a href="#">Book's infomation</a></li>
        </ul>
        <div class="session-form alt">
            <div class="form-field">
                <fieldset>
                    @Html.LabelFor(model => model.Title)
                    @Html.TextBoxFor(model => model.Title, new {@class = "form-text"})
                </fieldset>
                <p id="title_validation" class="message">
                    @Html.ValidationMessageFor(model => model.Title)
                </p>
            </div>
            <div class="form-field">
                <fieldset>
                    <label for="AuthorName">
                        Author Name</label>
                    @Html.TextBoxFor(model => model.AuthorName, new {@class = "form-text"})
                </fieldset>
                <p class="message">
                    @Html.ValidationMessageFor(model => model.AuthorName)
                </p>
            </div>
            <div class="form-field">
                <fieldset>
                    @Html.LabelFor(model => model.Tag)
                    @Html.TextBoxFor(model => model.Tag, new {@class = "form-text"})
                </fieldset>
                <p class="message">
                    @Html.ValidationMessageFor(model => model.Tag)
                </p>
            </div>
            <div class="form-field">
                <fieldset>
                    <label for="CategoryId">
                        Category</label>
                    @Html.DropDownListFor(model => model.CategoryId, categories)
                </fieldset>
            </div>
            <div class="form-field">
                <fieldset>
                    @Html.LabelFor(model => model.Description)
                    @Html.TextAreaFor(model => model.Description)
                </fieldset>
                <p class="message">
                    @Html.ValidationMessageFor(model => model.Description)
                </p>
            </div>
            <div class="form-btns">
                <input class="form-sub" id="saveButton" type="submit" value="Save" />
                <a class="form-btn" href="@returnUrl">Cancel</a>
            </div>
            @if (@Model.Chapters != null && @Model.Chapters.Count() > 0)
            {
                <div>
                    <a href="#" data-bind="click: editChapter"><span>Edit Chapters Number</span></a>
                    <input type="hidden" id="listSortedChapterId" name="listSortedChapterId"/>
                    <ol class="chapters group">
                        <div style="display: none" id="chapter-section" data-bind="template: {name:'ListChapterTemplate', foreach: chapterCollection}">
                        </div>
                    </ol>
                </div>
            }
        </div>
    </div>
    <div id="secondary">
        <h3>
            <span class="meta">Book's</span> Cover</h3>
        <div id="avatar-preview" class="group">
            <div class="form-field">
                <input type="hidden" id="filesUploaded" name="filesUploaded" />
            </div>
            <div id="upload_div">
                <fieldset>
                    <img  id="book_img" src="@imageUrl" width="180" height="200" />
                    <br />
                    <div>
                        <input id="file_upload" name="file_upload" type="file" />
                    </div>
                </fieldset>
            </div>
        </div>
    </div>
}
<script id="ListChapterTemplate" type="text/html">
    <li class="group" data-bind="attr: {'chapter-id': Id()}">
        <div class="dribbble">
            <div class="dribbble-shot">
                <div class="dribbble-img">
                    <a data-bind="attr: { href: '/chapters/details/'+ Id()}" class="dribbble-link">
                        <div style="text-align: center">
                            <img data-bind="attr: {src: ChapterImage}" height="150" />                                   
                        </div>
                    </a>
                    
                    
                </div>
                <ul class="tools group">
                    <li >Name:<span data-bind="text: ChapterName"></span></li>
                    <li >No:<span data-bind="text: chapterNumber"></span></li>
                </ul>
            </div>
            
        </div>
        
    </li>

</script>
<script type="text/javascript">
//    check exist BookName

    $("#Title").focusout(function() {
        var booktitle = $("#Title").val();
        $.ajax({
                url: '@Url.Action("ExistBookTitle", "Books")',
                type: 'POST',
                data: ko.toJSON({ title: booktitle, bookId: @Model.Id }),
                contentType: 'APPLICATION/JSON',
                success: function(result) {
                    if (!result.Valid) {
                        $("#title_validation").empty().html("<img src='../../Content/images/invalid-mark-20.png'/>" + result.Message);

                    }
                    ;
                    if (result.Valid) {
                        $("#title_validation").empty().html("<img src='../../Content/images/available-mark-20.png'/>Available");
                    }
                    ;
                }
            });

    });

    $(document).ready(function() {
        $("#chapter-section").sortable({
                connectWith: '.connectedSortable',
                forcePlaceholderSize: true,
                stop: function(event, ui) {

                    $("#listSortedChapterId").val('');
                    for (var i = 0; i < $('#chapter-section > .group').length; i++) {
                          $("#listSortedChapterId").val($("#listSortedChapterId").val()+";" +$($('#chapter-section > .group')[i]).attr("chapter-id"));
                    }
                  
                }
            }).disableSelection();
        $("#AuthorName").autocomplete("/Authors/Search", { minChars: 1 });
        $("#Tag").autocomplete("/Books/SearchContentTag", { minChars: 1, multiple: true });
        $("#file_upload").uploadify({
                'uploader': '/Scripts/uploadify/uploadify.swf',
                'script': '@Url.Action("UploadImage")',
                'fileDataName': 'FileData',
                'buttonText': 'Select files',
                'multi': false,
                'width': 120,
                'sizeLimit': 4000000,
                'simUploadLimit': 1,
                'cancelImg': '/Scripts/uploadify/cancel.png',
                'folder': '/Images',
                'fileExt': '*.jpg;*.gif;*.png',
                'fileDesc': 'Image Files',
                'auto': true,
                'removeCompleted': false,
                'onError': function(a, b, c, d) {
                    if (d.status == 404)
                        alert("Could not find upload script. Use a path relative to: " + "<?= getcwd() ?>");
                    else if (d.type === "HTTP")
                        alert("error " + d.type + ": " + d.status);
                    else if (d.type === "File Size")
                        alert(c.name + " " + d.type + " Limit: " + Math.round(d.info / (1024 * 1024)) + "MB");
                    else
                        alert("error " + d.type + ": " + d.text);
                },
                'onSelect': function(event, ID, fileObj) {
                    $('#saveButton').disabled = true;
                },
                'onComplete': function(event, queueId, fileObj, response, data) {
                    $("#filesUploaded").val(response);
                    $('#saveButton').disabled = false;
                     $("#book_img").attr("src", response);

                }
            });
    });

    function Chapter(id, chapterName, chapterImage, numberOfPage, content, chapterNumber) {
        return {
            Id: ko.observable(id),
            ChapterName: ko.observable(chapterName),
            ChapterImage: ko.observable(chapterImage),
            NumberOfPage: ko.observable(numberOfPage),
            Content: ko.observable(content),
            chapterNumber: ko.observable(chapterNumber)
        };
    }
    var listchapter = @CustomHelpers.ChapterToJavaScriptConverter(@Model.Chapters.ToList()) ;
    var viewmodel = {
        chapterCollection: ko.observableArray(listchapter),
        editChapter: function() {
            $('#chapter-section').toggle();
        }
    };
    ko.applyBindings(viewmodel);
</script>